<template>
    <div class="notice-management">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>公告管理</h2>
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon>新增公告
        </el-button>
      </div>
  
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索公告标题"
          class="search-input"
          clearable
          @keyup.enter="fetchNotices"
          @clear="fetchNotices"
        >
          <template #append>
            <el-button @click="fetchNotices">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
  
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="fetchNotices"
        />
      </div>
  
      <!-- 公告列表 -->
      <el-table
        :data="noticeList"
        border
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="标题" min-width="200">
          <template #default="{row}">
            <div class="title-cell" @click="showDetail(row)">
              <span class="title-text">{{ row.title }}</span>
              <el-icon class="detail-icon"><View /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="图片" width="120" align="center">
          <template #default="{row}">
            <el-image
              v-if="row.img"
              style="width: 80px; height: 60px"
              :src="row.img"
              :preview-src-list="[row.img]"
              fit="cover"
              preview-teleported
              hide-on-click-modal
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="day" label="发布日期" width="120" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{row}">
            <el-button size="small" @click="openEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchNotices"
          @current-change="fetchNotices"
        />
      </div>
  
      <!-- 公告详情对话框 -->
      <el-dialog
        v-model="detailVisible"
        :title="currentNotice.title"
        width="70%"
        top="5vh"
      >
        <div class="notice-detail">
          <div class="notice-meta">
            <span>发布日期: {{ currentNotice.day }}</span>
            <span v-if="currentNotice.author">作者: {{ currentNotice.author }}</span>
          </div>
          
          <el-image
            v-if="currentNotice.img"
            :src="currentNotice.img"
            fit="contain"
            style="max-height: 300px; margin-bottom: 20px;"
          />
          
          <div class="notice-content" v-html="currentNotice.content"></div>
        </div>
      </el-dialog>
  
      <!-- 新增/编辑公告对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑公告' : '新增公告'"
        width="50%"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入公告标题" />
          </el-form-item>
          
          <el-form-item label="发布日期" prop="day">
            <el-date-picker
              v-model="form.day"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="作者" prop="author">
            <el-input v-model="form.author" placeholder="请输入作者" />
          </el-form-item>
          
          <el-form-item label="图片链接" prop="img">
            <el-input v-model="form.img" placeholder="请输入图片URL">
              <template #append>
                <el-button @click="previewImage">预览</el-button>
              </template>
            </el-input>
            <el-image
              v-if="form.img"
              :src="form.img"
              style="width: 100px; height: 80px; margin-top: 10px;"
              fit="cover"
            />
          </el-form-item>
          
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="8"
              placeholder="请输入公告内容"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            确认
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { Plus, Search, View } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import axios from 'axios'
  
  // 数据状态
  const loading = ref(false)
  const noticeList = ref([])
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)
  const searchQuery = ref('')
  const dateRange = ref([])
  
  // 详情相关
  const detailVisible = ref(false)
  const currentNotice = ref({
    id: null,
    title: '',
    content: '',
    img: null,
    day: '',
    author: null
  })
  
  // 表单相关
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const submitting = ref(false)
  const formRef = ref(null)
  const form = ref({
    id: null,
    title: '',
    content: '',
    img: null,
    day: '',
    author: null
  })
  
  // 表单验证规则
  const rules = {
    title: [
      { required: true, message: '请输入公告标题', trigger: 'blur' },
      { min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur' }
    ],
    content: [
      { required: true, message: '请输入公告内容', trigger: 'blur' }
    ],
    day: [
      { required: true, message: '请选择发布日期', trigger: 'change' }
    ]
  }
  
  // 获取公告列表
  const fetchNotices = async () => {
    try {
      loading.value = true
      const response = await axios.get('http://localhost:8080/hospital5_war/notice/findAll')
      noticeList.value = response.data || []
      total.value = noticeList.value.length
      
      // 前端筛选
      if (searchQuery.value) {
        noticeList.value = noticeList.value.filter(item => 
          item.title.includes(searchQuery.value))
      }
      
      if (dateRange.value && dateRange.value.length === 2) {
        const [start, end] = dateRange.value
        noticeList.value = noticeList.value.filter(item => 
          item.day >= start && item.day <= end)
      }
      
    } catch (error) {
      console.error('获取公告列表失败:', error)
      ElMessage.error('获取公告列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 查看详情
  const showDetail = (notice) => {
    currentNotice.value = { ...notice }
    detailVisible.value = true
  }
  
  // 打开新增对话框
  const openAddDialog = () => {
    isEdit.value = false
    form.value = {
      id: null,
      title: '',
      content: '',
      img: null,
      day: new Date().toISOString().split('T')[0],
      author: null
    }
    dialogVisible.value = true
  }
  
  // 打开编辑对话框
  const openEditDialog = (notice) => {
    isEdit.value = true
    form.value = { ...notice }
    dialogVisible.value = true
  }
  
  // 预览图片
  const previewImage = () => {
    if (form.value.img) {
      window.open(form.value.img, '_blank')
    }
  }
  
  // 提交表单
  const submitForm = async () => {
    try {
      await formRef.value.validate()
      submitting.value = true
      
      if (isEdit.value) {
        await axios.post('http://localhost:8080/hospital5_war/notice/updateNotice', form.value)
        ElMessage.success('公告更新成功')
      } else {
        await axios.post('http://localhost:8080/hospital5_war/notice/addNotice', form.value)
        ElMessage.success('公告添加成功')
      }
      
      dialogVisible.value = false
      fetchNotices()
    } catch (error) {
      console.error('操作失败:', error)
      if (error.response?.status === 404) {
        ElMessage.error('未找到对应公告')
      } else {
        ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试')
      }
    } finally {
      submitting.value = false
    }
  }
  
  // 删除公告
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除该公告吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      await axios.delete(`http://localhost:8080/hospital5_war/notice/deleteNotice/${id}`)
      ElMessage.success('公告删除成功')
      fetchNotices()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败:', error)
        ElMessage.error(error.response?.data?.message || '删除失败')
      }
    }
  }
  
  // 初始化加载数据
  onMounted(() => {
    fetchNotices()
  })
  </script>
  
  <style scoped>
  .notice-management {
    padding: 20px;
    background-color: #fff;
  }
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .filter-container {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
  }
  
  .search-input {
    width: 300px;
  }
  
  .title-cell {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
  
  .title-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .detail-icon {
    margin-left: 10px;
    color: #409eff;
  }
  
  .notice-detail {
    padding: 0 20px;
  }
  
  .notice-meta {
    margin-bottom: 20px;
    color: #666;
    font-size: 14px;
    display: flex;
    gap: 20px;
  }
  
  .notice-content {
    line-height: 1.8;
  }
  
  .notice-content :deep(p) {
    margin-bottom: 15px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>